// pages/mine/mine.js
var db = wx.cloud.database();
var userCollection = db.collection("usersDataList");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    meaningShow: false,
    userDataList: [],
    isShared: false,
    homeFlag: 0,
  },
  // 计算年龄的方法
  calculateAge(birthDate) {
    try {
      if (!birthDate) return "未知";

      // 兼容性日期解析
      const parseDate = (dateStr) => {
        const normalized = dateStr.replace(/-/g, "/");
        const parts = normalized.split("/");
        if (parts.length === 3) {
          parts[1] = parts[1].padStart(2, "0");
          parts[2] = parts[2].padStart(2, "0");
          return new Date(parts.join("/"));
        }
        return new Date(normalized);
      };

      const birth = parseDate(birthDate);
      const now = new Date();

      if (isNaN(birth.getTime())) {
        console.error("无效的日期格式:", birthDate);
        return "未知";
      }

      if (birth > now) {
        console.error("出生日期不能晚于当前日期");
        return "未知";
      }

      let years = now.getFullYear() - birth.getFullYear();
      let months = now.getMonth() - birth.getMonth();

      if (now.getDate() < birth.getDate()) {
        months--;
      }

      if (months < 0) {
        years--;
        months += 12;
      }

      if (years < 0) return "未知";

      // 优化显示逻辑：当月份为0时不显示
      return months > 0 ? `${years}岁${months}个月` : `${years}岁`;
    } catch (error) {
      console.error("计算年龄时发生错误:", error);
      return "未知";
    }
  },
  goHomePage() {
    wx.navigateTo({
      url: "/pages/index/index",
    });
  },
  addUpdateMsg() {
    wx.navigateTo({
      url: "/pages/updateMsg/updateMsg",
    });
  },
  updateMsg(e) {
    const userData = this.data.userDataList[e.currentTarget.dataset.index];
    wx.navigateTo({
      url: `/pages/updateMsg/updateMsg?userData=${JSON.stringify(userData)}`,
    });
  },
  toggleSearchShow() {
    this.setData({
      meaningShow: false,
    });
  },
  showMeaning() {
    this.setData({
      meaningShow: true,
    });
  },
  getData() {
    const openid = wx.getStorageSync("openid");
    if (!openid) {
      console.error("未获取到openid");
      return;
    }
    userCollection
      .where({
        _openid: openid,
      })
      .get({
        success: (res) => {
          console.log("获取数据成功：", res.data);
          if (res.data && res.data.length > 0) {
            const records = res.data[0].records;
            // 处理每条记录的年龄显示
            records.forEach((record) => {
              if (record.birthDate) {
                record.ageDisplay = this.calculateAge(record.birthDate);
              }
            });
            this.setData(
              {
                userDataList: records,
              },
              () => {
                console.log("数据更新完成：", this.data.userDataList);
              }
            );
          } else {
            console.log("未找到用户数据");
            this.setData({
              userDataList: [],
            });
          }
        },
        fail: (err) => {
          console.error("获取数据失败：", err);
          wx.showToast({
            title: "获取数据失败",
            icon: "none",
          });
        },
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 判断是否为分享进入
    const isShared = wx.getStorageSync("isShared");
    const homeFlag = wx.getStorageSync("homeFlag") || 0;
    this.setData({
      isShared: isShared === true,
      homeFlag: homeFlag,
    });

    if (!isShared && homeFlag !== 1) {
      this.getData();
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},

  // 处理首页跳转
  goHomepage(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error("事件参数无效");
      return;
    }

    const value = e.currentTarget.dataset.flag;
    console.log("跳转标志：", value);

    if (value == 2) {
      // 打开我的防控档案
      this.clearSharedData();
      wx.setStorageSync("homeFlag", value);
      wx.switchTab({
        url: "/pages/home/home",
      });
    } else if (value == 1) {
      // 返回按钮处理
      if (!this.data.isShared) {
        // 如果不是分享数据，才清除分享数据
        this.clearSharedData();
      }
      wx.setStorageSync("homeFlag", value);
      wx.switchTab({
        url: "/pages/home/home",
      });
    }
  },

  // 清除分享相关的存储数据
  clearSharedData() {
    try {
      // 检查并清除 sharedOpenid
      if (wx.getStorageSync("sharedOpenid")) {
        wx.removeStorageSync("sharedOpenid");
      }
      // 检查并清除 sharedUserId
      if (wx.getStorageSync("sharedUserId")) {
        wx.removeStorageSync("sharedUserId");
      }
      // 设置分享状态为 false
      wx.setStorageSync("isShared", false);
    } catch (error) {
      console.error("清除分享数据失败：", error);
      wx.showToast({
        title: "操作失败，请重试",
        icon: "none",
      });
    }
  },

  /**
   * 获取用户手机号
   */
  onGetPhoneNumber(e) {
    console.log(e);
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      wx.cloud.callFunction({
        name: "getPhoneNumber", // 你需要创建的云函数名
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        },
        success: (res) => {
          wx.showToast({ title: "手机号获取成功", icon: "success" });
          console.log("手机号解密结果", res);
          // 这里可以将手机号存入数据库或做后续处理
        },
        fail: (err) => {
          wx.showToast({ title: "获取手机号失败", icon: "none" });
          console.error("手机号解密失败", err);
        },
      });
    } else {
      wx.showToast({ title: "用户未授权手机号", icon: "none" });
    }
  },
});
